package monster.com.cvh.fragment;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.text.InputFilter;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import monster.com.cvh.R;
import monster.com.cvh.activity.LoginActivity;
import monster.com.cvh.activity.MainActivity;
import monster.com.cvh.bean.LoginBean;
import monster.com.cvh.bean.QqLoginBean;
import monster.com.cvh.bean.WcLoginBean;
import monster.com.cvh.constant.Constans;
import monster.com.cvh.event.VisitorRefreshEvent;
import monster.com.cvh.util.MyConstant;
import monster.com.cvh.util.SPUtils;
import okhttp3.Call;
import okhttp3.Response;

/**
 * @author: 13580
 * @data: 2018/3/7
 * @function:
 */

public class LoginFragment extends monster.com.cvh.fragment.base.BaseFragment {
    private static final String TAG = "LoginFragment";
    @BindView(R.id.edt_activity_login_phone)
    EditText mEdtLoginPhone;
    @BindView(R.id.edt_activity_login_password)
    EditText mEdtLoginPassword;
    @BindView(R.id.iv_activity_login_see)
    ImageView mIvSeePassword;
    private Boolean showPassword = true;
    private Gson gson;
    private ProgressDialog mDialog;
    /**
     * 微信的回调
     */
    UMAuthListener mUmAuthListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {
            Log.i(mTag, "onStart: " + "微信开始回调");
        }

        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> data) {
            final String weixin_openId = data.get("openid");
            final String weixin_name = data.get("name");
            final String iconurl = data.get("iconurl");
            OkGo.<String>post(MyConstant.WECHAT_LOGIN).params("wx_openid", weixin_openId).params("wx_name", weixin_name).execute(new StringCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                   try {
                       WcLoginBean wxLoginBean = gson.fromJson(s, WcLoginBean.class);
                       //id token 存入token
                       if (getActivity() != null) {
                           SPUtils.putString(getActivity(),"displayId",wxLoginBean.getData().getWxInfo().get(0).getDisplayId());
                           SPUtils.putString(getActivity(), "token", wxLoginBean.getData().getWxInfo().get(0).getToken());
                           SPUtils.putInt(getActivity(), "id", wxLoginBean.getData().getWxInfo().get(0).getUserId());
                           SPUtils.putString(getActivity(), "iconUrl", wxLoginBean.getData().getWxInfo().get(0).getIconUrl());
                           SPUtils.putString(getActivity(), "userName", wxLoginBean.getData().getWxInfo().get(0).getName());
                           switch (wxLoginBean.getCode()) {
                               case 1:
                                   VisitorRefreshEvent.getInstance().onVisitorLogin();
                                   Intent intentMain = new Intent(getActivity(), MainActivity.class);
                                   intentMain.putExtra("userIntro", wxLoginBean.getData().getWxInfo().get(0).getSelfIntro());
                                   FragmentActivity activity = getActivity();
                                   if (activity instanceof LoginActivity) {
                                       Log.i(TAG, "onSuccess: ");
                                   }
                                   startActivity(intentMain);
                                   mDialog.dismiss();
                                   Log.e(TAG, "微信登录: ");
                                   getActivity().finish();
                                   break;
                               case -1004:
                                   showToastLong( "登录失败");
                                   break;
                               case -1007:
                                   showToastLong( "您的账号违规，禁止登陆，请联系管理员");
                                   break;
                           }
                       }else {
                           Log.e(TAG, "onSuccess: "+"登录失败" );
                       }
                   }catch (Exception e) {
                       if (getActivity() != null) {
                           showToastLong("登录失败，稍后重试");
                       }
                       return;
                   }

                }
            });

        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
            showToastShort("授权失败");
            Log.i("lixiaofei", "onError: " + throwable.toString());
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {
            showToastShort("授权取消");
        }
    };
    /**
     * QQ的回调
     */
    UMAuthListener qqUmAuthListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {
            Log.i(mTag, "onStart: " + "QQ开始回调");
        }

        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> data) {
            final String qq_name = data.get("name");
            String qq_openid = data.get("openid");
            final String iconurl = data.get("iconurl");
            OkGo.<String>post(MyConstant.QQ_LOGIN).params("qq_openid", qq_openid).params("qq_name", qq_name).execute(new StringCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                   try {
                       QqLoginBean qqLoginBean = gson.fromJson(s, QqLoginBean.class);
                       //id token 存入sp
                       SPUtils.putString(getActivity(), "displayId", qqLoginBean.getData().getQqInfo().get(0).getDisplayId());
                           SPUtils.putString(getActivity(), "token", qqLoginBean.getData().getQqInfo().get(0).getToken());
                           SPUtils.putInt(getActivity(), "id", qqLoginBean.getData().getQqInfo().get(0).getUserId());
                           SPUtils.putString(getActivity(), "iconUrl", qqLoginBean.getData().getQqInfo().get(0).getIconUrl());
                           SPUtils.putString(getActivity(), "userName", qqLoginBean.getData().getQqInfo().get(0).getName());
                           switch (qqLoginBean.getCode()) {
                               case 1:
                                   VisitorRefreshEvent.getInstance().onVisitorLogin();
                                   Intent intentMain = new Intent(getActivity(), MainActivity.class);
                                   Log.i("lixiaofei", "onSuccess: " + qqLoginBean.getData().getQqInfo().get(0).getToken());
                                   if (!(getContext() instanceof Activity)){
                                       intentMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                   }
                                   intentMain.putExtra("userIntro", qqLoginBean.getData().getQqInfo().get(0).getSelfIntro());
                                   startActivity(intentMain);
                                   mDialog.dismiss();
                                   getActivity().finish();
                                   break;
                               case -1004:
                                   showToastLong("登录失败");
                                   break;
                               case -1007:
                                   showToastLong("您的账号违规，禁止登陆，请联系管理员");
                                   break;
                           }
                   }catch (Exception e) {
                       if (getActivity() != null) {
                           showToastLong("登录失败，稍后重试");
                       }
                       return;
                   }

                }
            });
        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
            showToastShort("授权失败");
            Log.i("lixiaofei", "onError: " + throwable.toString());
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {
            showToastShort("授权取消");
        }
    };
    private int mVisitorCode = -1;
    private List<View> mViews;

    public static LoginFragment newIntance(int code) {
        Bundle args = new Bundle();
        args.putInt(Constans.VISITOR, code);
        LoginFragment fragment = new LoginFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null) {
            mVisitorCode =args.getInt(Constans.VISITOR);
        }
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_login;
    }

    @Override
    protected void initData() {
        mViews = new ArrayList<>();
        mDialog = new ProgressDialog(getActivity());
        mDialog.setMessage(getResources().getString(R.string.wait));
        mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                //回退键监听
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                }
                return false;
            }
        });
        mDialog.setCanceledOnTouchOutside(false);
        gson = new Gson();
        UMShareConfig config = new
                UMShareConfig();

        config.isNeedAuthOnGetUserInfo(true);

        UMShareAPI.get(getActivity()).setShareConfig(config);

    }



    @Override
    protected void initEvent() {
        //限制手机号码字数为11位
        mEdtLoginPhone.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
    }
    /**
     * 隐藏软键盘(可用于Activity，Fragment)
     */
    public static void hideSoftKeyboard(Context context, List<View> viewList) {
        if (viewList == null) return;

        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);

        for (View v : viewList) {
            inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
    private void login() {
        //登录
        mDialog.show();
        OkGo.<String>post(MyConstant.PHONE_LOGIN).params("phone", mEdtLoginPhone.getText().toString().trim()).params("pwd", mEdtLoginPassword.getText().toString().trim())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            LoginBean phoneLoginBean = gson.fromJson(s, LoginBean.class);
                            switch (phoneLoginBean.getCode()) {
                                case 1:
                                    VisitorRefreshEvent.getInstance().onVisitorLogin();
                                    //登录成功
                                        LoginBean.DataBean data = phoneLoginBean.getData();
                                        SPUtils.putString(getActivity(),"displayId",data.getUserInfo().get(0).getDisplayId());
                                        SPUtils.putString(getActivity(), "token", data.getUserInfo().get(0).getToken());
                                        SPUtils.putInt(getActivity(), "id", data.getUserInfo().get(0).getUserId());
                                        SPUtils.putString(getActivity(), "iconUrl", data.getUserInfo().get(0).getIconUrl());
                                        SPUtils.putString(getActivity(), "userName", data.getUserInfo().get(0).getName());
                                        Intent intentMain = new Intent(getActivity(), MainActivity.class);
//                                intentMain.putExtra("userName", data.getUserInfo().get(0).getName());
                                        if (!(getContext() instanceof Activity)){
                                            intentMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        }
                                        intentMain.putExtra("userIntro", data.getUserInfo().get(0).getSelfIntro());
                                        startActivity(intentMain);
                                        mDialog.dismiss();
                                        //隐藏软键盘
                                        mViews.add(mEdtLoginPassword);
                                        mViews.add(mEdtLoginPhone);
                                        hideSoftKeyboard(getActivity(), mViews);
                                        getActivity().finish();
                                    break;
                                case 2:
                                    //手机号码输入错误
                                    showToastLong("手机号码输入错误");
                                    mDialog.dismiss();
                                    break;
                                case 6:
                                    showToastLong("密码输入错误");
                                    mDialog.dismiss();
                                    break;
                                case 23:
                                    showToastLong("该手机未注册");
                                    mDialog.dismiss();
                                    break;
                                case -1004:
                                    showToastLong("请将信息填写完整");
                                    mDialog.dismiss();
                                    break;
                                case -1007:
                                    showToastLong("您的账号违规，禁止登陆，请联系管理员");
                                    break;
                            }
                        }catch (Exception e) {
                            if (getActivity() != null){
                                showToastLong("登录失败，稍后重试");
                            }

                            return;
                        }

                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        mDialog.dismiss();
                    }
                });
    }

    @OnClick({
            R.id.tv_login_no_password, R.id.tv_forget_password, R.id.iv_activity_login_see,
            R.id.tv_activity_login_loging, R.id.tv_activity_login_register, R.id.ll_activity_login_qq,
            R.id.ll_activity_login_wechat
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_login_no_password:
                //清除之前的用户数据
                if (getActivity() != null) {
                    SPUtils.removeBykey(getActivity(), "token");
                    SPUtils.removeBykey(getActivity(), "id");
                    SPUtils.removeBykey(getActivity(), "iconUrl");
                    SPUtils.removeBykey(getActivity(), "userName");
                    Intent intent = new Intent(getActivity(), MainActivity.class);
                    startActivityForResult(intent, Constans.LOGIN_WITHOUT_OPTION);
                    getActivity().finish();
                }else {
                    Log.e(TAG, "onViewClicked: "+"登录失败" );
                }
                break;
            case R.id.tv_forget_password:
                //忘记密码fragment
                FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                fragmentTransaction.setCustomAnimations(R.anim.slide_right_in, R.anim.slide_left_out, R.anim.slide_left_in, R.anim.slide_right_out);
                fragmentTransaction.replace(R.id.cfl_content, new ResetPasswordFragment());
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case R.id.tv_activity_login_register:
                //注册fragment
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.setCustomAnimations(R.anim.slide_right_in, R.anim.slide_left_out, R.anim.slide_left_in, R.anim.slide_right_out);
                transaction.replace(R.id.cfl_content, new RegisterFragment());
                transaction.addToBackStack(null);
                transaction.commit();
                break;
            case R.id.iv_activity_login_see:
                //显示密码
                if (showPassword) {
                    mIvSeePassword.setImageResource(R.mipmap.login_see);
                    mEdtLoginPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    mEdtLoginPassword.setSelection(mEdtLoginPassword.getText().toString().length());
                    showPassword = !showPassword;
                } else {
                    //隐藏密码
                    mEdtLoginPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    mEdtLoginPassword.setSelection(mEdtLoginPassword.getText().toString().length());
                    mIvSeePassword.setImageResource(R.mipmap.login_notsee);
                    showPassword = !showPassword;
                }
                break;
            case R.id.tv_activity_login_loging:
                //登录
                login();
                break;
            case R.id.ll_activity_login_qq:
                //QQ登录
                mDialog.show();
                if (getActivity() != null) {
                    UMShareAPI.get(getActivity()).getPlatformInfo(getActivity(), SHARE_MEDIA.QQ, qqUmAuthListener);
                }else {
                    Log.e(TAG, "onViewClicked: "+"登录失败" );
                }
                break;
            case R.id.ll_activity_login_wechat:
                //微信登录
                Log.i(TAG, "onViewClicked: "+"调用微信登陆");
                mDialog.show();
                if (getActivity() != null) {
                    UMShareAPI.get(getActivity()).getPlatformInfo(getActivity(), SHARE_MEDIA.WEIXIN, mUmAuthListener);
                }else {
                    Log.i(TAG, "onViewClicked:"+"登录失败s");
                }
                break;
        }
    }
}
